setScreenMetrics(device.width, device.height);

app_func = {
    appName : "快手极速版" ,
    packageName : "com.kuaishou.nebula",
    mainActivity : "com.yxcorp.gifshow.webview.KwaiWebViewActivity",
    videoActivity : "com.yxcorp.gifshow.HomeActivity" ,
    bounds:{
        task_button : null
    },
    thread : null ,
    stopflag : null
}

let current_package = "com.kuaishou.nebula";
function launchAppEnhance(app_name){
    let result;
    let thread = threads.start(function(){
        toastLog("检查是否有打开权限!");
        while(true) {
            var allow = text("允许").findOne(5000);
            if(allow){
                sleep(1000)
                toastLog("发现允许授权!");
                allow.click();
                sleep(1000);
                thread.interrupt();
                break;
            }
        } 
    });
    sleep(1000);
    if (currentPackage() != current_package) {
        result = launchApp(app_name);
        sleep(3000);
    }
    else{
        result = currentPackage();
    }
    thread.interrupt();
    return result;
}

function find_task_button(){
    var sucflag = 0
    //console.log("开始寻找任务按钮------------------:");
    var task_button =  text("任务").findOne(5000);
    for( var i = 0 ; i < 3 ;i++ ){
        if( task_button ){       
            toastLog("控件text:",task_button.text() );
            app_func.bounds.task_button = task_button.bounds()
            sucflag = 1 ;
            break;
        }
        else{
            toastLog("没找到任务界面");
            // 关广告  各种返回到首页
            clean_obs()
            continue;
        }
    }
    if(sucflag == 0 ){
        return -1;
    }
    
    return 0;
}

//关闭各种弹窗广告
function close_all_ad(){
    try{ text('我知道了').findOne(500).click(); } catch(e){}
    try{ text('跳过').findOne(500).click();} catch(e){}
    try{ text('禁止').findOne(500).click();} catch(e){}
    try{ text('以后再说').findOne(500).click();} catch(e){}
 
    try{ 
        无关闭控件广告 = text("点击重播").findOne(500)
        if( 无关闭控件广告 ){
            toastLog("5")
            text("关注").findOne(500).click()
            text("发现").findOne(500).click()
        }
    } catch(e){}

    try{ 
        关闭按钮 = id("close_btn").findOne(500)
        if( 关闭按钮 ){
            toastLog("1")
            关闭按钮.click( )
        }
    } catch(e){}
}

function click_close() {
    let close = text("点击关闭").findOne(4000);
    if(close) {
        sleep(1000);
        close.click();
    }
}

//清除各种障碍 直到主界面
function clean_obs(){
    var result = null

    if( is_mainAct() ){
        //关闭各种广告
        close_all_ad()
        result = 0
    }
    else{
        //存在是在主页 也有弹窗
        result = err_back()
    }
    return result
}

function is_mainAct(){
    sleep(1000)
    var curact = currentActivity();
    if( curact != app_func.mainActivity ){
        toastLog("不在主界面")
        return false
    }
    else{
        toastLog("当前是主界面")
        return true
    }
}

function is_videoAct(){
    sleep(1000)
    var curact = currentActivity();
    if( curact != app_func.videoActivity ){
        toastLog("不在视频界面")
        return false
    }
    else{
        toastLog("当前是视频")
        return true
    } 
}

function err_back(){
    var curact = null;
    for( var i=0; i < 3 ; i++ ){
        curact = currentActivity()
        sleep(1000)
        if( curact != app_func.mainActivity ){
            toastLog("尝试回到主界面")
            back();
            sleep(3000)
        }
        else{
            toastLog("已回到当前主界面") 
            break
        }
    }

    if( curact != app_func.mainActivity ){
        toastLog("回主界面失败")
        return -1
    }

    return 0
}

//关闭广告按钮
function find_close_adv_button(){
    toastLog("开始寻找关闭广告按钮------------------:");
    var target_button =  text("关闭广告").findOne(2*1000);
    if( target_button ){       
        toastLog("控件text:",target_button.text() );
        click_button( target_button.bounds() )
        return 0;
    }
    else{
        toastLog("没找到关闭广告按钮");
        return -1;
    }
}

function find_button_by_text( textstr ){
    toastLog("寻找按钮:"+ textstr );
    var task_button =  null
    for( var i = 0 ; i < 1 ;i++ ){
        task_button =  text( textstr ).findOne(3000);
        if( task_button ){       
            console.log("找到控件text:",task_button.text() );
            break;
        }
        else{
            console.log("第"+ (i+1) + "次未找到" );
            sleep(1000)
            continue;
        }
    }

    return task_button
}

function find_button_by_textStartsWith( textstr ){
    toastLog("寻找按钮:"+ textstr );
    var task_button =  null
    for( var i = 0 ; i < 1 ;i++ ){
        task_button =  textStartsWith( textstr ).findOne(1000);
        if( task_button ){       
            console.log("找到控件text:",task_button.text() );
            break;
        }
        else{
            console.log("第"+ (i+1) + "次未找到" );
            sleep(1000)
            continue;
        }
    }
    sleep(1000)
    return task_button
}

//传入坐标参数
function click_button( bounds ){
    toastLog("点击按钮:"+bounds.centerX()+ bounds.centerY()  );
    sleep(1000);
    click(bounds.centerX(), bounds.centerY() );
    sleep(2000)
}

function open_baoxiang(){
    var baoxiang =  text("开宝箱得金币").findOne(5000);
    if(baoxiang){
        toastLog("开始点击开宝箱");
        sleep(1000);
        click_button( baoxiang.bounds() );
        sleep(5000);
        return 0
    }
    else{
        toastLog("没有发现开宝箱得金币");
        return -1
    }
}


function find_X_adv_button(){
    var close = id("reward_ad_close").findOne(5000) || id("tt_video_ad_close_layout").findOne(2000);
    if(close){
        toastLog("发现关闭按钮");
        sleep(1000);
        close.click();
        return 0
    }
}

function handle_after_more_reward(){
    for(var i = 0 ; i < 70 ; i++){
        sleep(1000)
        //每5秒检查一次关闭按钮是否出现
        if( (i+1) % 5 == 0 ){
            console.log( "检查是否出现退出按钮" );
            // X按钮
            if( find_X_adv_button() >= 0 ){                
                return 0
            }
            //关闭广告按钮
            if( find_close_adv_button() >= 0 ){
                return 0
            }

            let video_red_pocket = text("视频红包").findOne(1000);
            let 恭喜获得 = textMatches("恭喜获得\\d+元").findOne(1000);
            if( video_red_pocket || 恭喜获得 ){
                toastLog("广告已关闭")
                return 0
            }
        }    
    }
    return -1; 
}

//向下滑
function _down_move(){
    console.log("向下滑动" )
    let x = device.width/2
    ,   t = device.height * 4/5
    ,   b = device.height * 1/5
    sml_move(x, b, x, t, 200 + random(50,100));
    sleep(1000);
}
//向上滑
function _up_move(){
    console.log("向上滑动" )
    let x = device.width/2
    ,   t = device.height * 1/5
    ,   b = device.height * 4/5
    sml_move(x, b, x, t, 200+ random(50,100));
    sleep(1000);
}

//向左滑
function _left_move(){
    console.log("向左滑动" )
    let y = device.height/2
    ,   t = device.width * 1/5
    ,   b = device.width * 4/5
    sml_move(b , y, t, y, 200 + random(50,100));
    sleep(1000);
}

//向右滑
function _rigth_move(){
    console.log("向右滑动" )
    let y = device.height/2
    ,   t = device.width * 4/5
    ,   b = device.width * 1/5
    sml_move(b , y, t, y, 200 + random(50,100));
    sleep(1000);
}

function sml_move(qx, qy, zx, zy, time) {
    //仿真随机带曲线滑动: qx, qy, zx, zy, time 代表起点x,起点y,终点x,终点y,过程耗时单位毫秒
    var xxy = [time];
    var point = [
        {"x": qx,"y": qy},
        {"x": random(qx - 100, qx + 100), "y": random(qy , qy + 50)},
        {"x": random(zx - 100, zx + 100), "y": random(zy , zy + 50)},
        {"x": zx,"y": zy}
    ];
    for (let i = 0; i < 1; i += 0.08) {
        xxyy = [parseInt(bezier_curves(point, i).x), parseInt(bezier_curves(point, i).y)]
        xxy.push(xxyy);
    }
    gesture.apply(null, xxy);
}

function bezier_curves(cp, t) {
    cx = 3.0 * (cp[1].x - cp[0].x); 
    bx = 3.0 * (cp[2].x - cp[1].x) - cx; 
    ax = cp[3].x - cp[0].x - cx - bx; 
    cy = 3.0 * (cp[1].y - cp[0].y); 
    by = 3.0 * (cp[2].y - cp[1].y) - cy; 
    ay = cp[3].y - cp[0].y - cy - by; 
    
    tSquared = t * t; 
    tCubed = tSquared * t; 
    result = {"x": 0, "y": 0};
    result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x; 
    result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y; 
    return result; 
};

//自动调整按钮位置并点击  适用于在屏幕外无法点击的按钮
function auto_find_button( textstr ) {
    var targetbutton = find_button_by_textStartsWith( textstr )
    var trytimes = 3
    if( targetbutton ){
        toastLog( "device.width:"+device.width+"device.height:"+device.height)
        toastLog( "x:"+targetbutton.bounds().centerX() +"y:"+ targetbutton.bounds().centerY() )
        //至少把空间拖到 屏幕 device.height * 1/5   至  device.height * 4/5 之间
        while(  targetbutton.bounds().centerY() > device.height * 4/5 ){
            var uptimes = Math.ceil( ( targetbutton.bounds().centerY() -  device.height * 4/5 )/ ( device.height * 4/5 - device.height * 1/5 ) )
            toastLog("需要滑动调整位置次数:" + uptimes )
            for( var i = 0 ; i < uptimes ; i++ ){
                _up_move()
                sleep(2000)
            }
            targetbutton = find_button_by_textStartsWith( textstr )
            trytimes--
            if( trytimes <=0 ){
                break
            }
        }

        while(  targetbutton.bounds().centerY() < device.height * 1/5 ){
            var uptimes = Math.ceil( ( device.height * 1/5 -  targetbutton.bounds().centerY() )/ ( device.height * 4/5 - device.height * 1/5 ) )
            toastLog("需要滑动调整位置次数:" + uptimes )
            for( var i = 0 ; i < uptimes ; i++ ){
                _down_move()
                sleep(2000)
            }
            targetbutton = find_button_by_textStartsWith( textstr )
            trytimes--
            if( trytimes <=0 ){
                break
            }
        }

        targetbutton = find_button_by_textStartsWith( textstr )
        if( targetbutton ){
            toastLog( "找到按钮:" + textstr )
        }
        else{
            toastLog("没找到按钮:" + textstr )
        }
    }
    return targetbutton
}

function handle_watch_vid_single_task( ){
    toastLog("看视频再奖励任务");
    //签到成功触发看视频再奖励按钮
    var strlist = [ "看视频再领" , "看视频领取" ]
    var 看视频再奖励 = null
    for( var i = 0 ;i < strlist.length ; i++ ){
        看视频再奖励 = find_button_by_textStartsWith( strlist[i] )
        if(看视频再奖励){
            break;
        }
    }
    if( 看视频再奖励 ){
        click_button( 看视频再奖励.bounds() )
        if( handle_after_open_vid() >= 0 ){
            toastLog( "签到视频奖励完成")
        }
        else{
            toastLog( "签到视频奖励失败")
            return -1
        }
    }
    else{
        //看视频再奖励流程失败
        toastLog("看视频再奖励流程失败");
        return -1
    }
    return 0 
}

function handle_sign_task(){
    //点击红包自动签到    //变成点击签到
    var thread1 = threads.start(function(){
        toastLog("检查恭喜获得好友看视频奖励")
        var widget = text("恭喜获得好友看视频奖励").findOne();
        if (widget) {
            toastLog("发现恭喜获得好友看视频奖励")
            back();
            dianji_hongbao();
            thread1.interrupt()
        }
    });
    
    var thread2 = threads.start(function(){
        var widget = text("我知道了").findOne(1000);
        if (widget) {
            widget.click();
            thread2.interrupt();
        }
    });

    var thread3 = threads.start(function(){
        toastLog("检查每邀请一个好友可得现金")
        var widget = text("每邀1个好友可得现金").findOne();
        if (widget) {
            toastLog("发现每邀1个好友可得现金");
            sleep(1000);
            var close = id("close").findOne(1000);
            if(close){
                sleep(1000);
                toastLog("找到关闭按钮！");
                close.click();
            }
            thread3.interrupt();
        }
    });

    var thread4 = threads.start(function(){
        var widget = id("close_view").findOne(1000);
        if (widget) {
            widget.click();
            thread4.interrupt();
        }
    });

    //滑块检查
    var thread5 = threads.start(function(){
        toastLog("滑动验证码检查")
        var widget = text("拖动滑块").findOne(1000);
        if (widget) {
            sleep(1000);
            openScreenCapture();
            dragSlider();
        }
    });

    var check_result = null;
    sleep(20*1000)
    for( var i=0;i<2;i++){
        dianji_hongbao();
        var 重试 = text("重试").findOne(2000)
        if( 重试 ){
            重试.click() 
        }
        //点击红包自动签到
        check_result = check_sign_success();
        if (check_result) {
            thread1.interrupt();
            thread2.interrupt();
            thread3.interrupt();
            thread4.interrupt();
            thread5.interrupt();
            return 0;
        }
    }

    thread1.interrupt();
    thread2.interrupt();
    thread3.interrupt();
    thread4.interrupt();
    thread5.interrupt();
    if( check_result == null ){
        return -1
    }

    //寻找立即签到弹窗
    立即签到 = find_button_by_textStartsWith("立即签到")
    if( 立即签到 ){
        click_button( 立即签到.bounds() )
        toastLog("签到完成")
        打开签到提醒 = find_button_by_textStartsWith("打开签到提醒")
        if( 打开签到提醒 ){
            关闭按钮 = 打开签到提醒.parent().child(0).click()
        }
        return 0
    }
    else{
        去签到 = find_button_by_textStartsWith("去签到")
        if(去签到){
            click_button( 去签到.bounds() )
            toastLog( "签到已经完成")
            return 0
        }
        else{
            已连续签到 = find_button_by_textStartsWith("已连续签到")
            if(已连续签到){
                toastLog( "签到已经完成")
                return 0
            }
            else{
                toastLog( "签到已经完成")
                return -1
            }
        }
    }  
}

function openScreenCapture(){
    let thread1 = threads.start(function(){
        toastLog("检查请求截屏!")
        var began = text("立即开始").findOne();
        if(began){
            sleep(1000)
            toastLog("发现请求截屏！");
            began.click();
            sleep(1000);
            thread1.interrupt();
        }
    });
    sleep(1000);
    if(!requestScreenCapture()){
        toastLog("请求截图失败!");
        exit();
    }
    else{
        toastLog("请求截图成功!");
    }
}

function dragSlider() {
    var 拖动滑块x = 123;
    var 拖动滑块y = 976.5;
    向右拖动 = find_button_by_textStartsWith("向右拖动滑块")
    滑块 = 向右拖动.parent().child(1)

    //滑块坐标 = "Rect(34, 597 - 130, 695)"
    // var 滑块 = className("android.view.View").depth("10").indexInParent("0").packageName("com.kuaishou.nebula").findOne(3000) || 
    //             className("android.view.View").depth("15").indexInParent("0").packageName("com.kuaishou.nebula").findOne(3000)
    if(滑块){
        toastLog("找到滑块")
        拖动滑块x = 滑块.bounds().centerX()
        拖动滑块y = 滑块.bounds().centerY()

        //  拖动滑块x = 滑块坐标.centerX()
        //  拖动滑块y = 滑块坐标.centerY()
        toastLog( "x:"+ 拖动滑块x + "y:" + 拖动滑块y )
    }
    else{
        toastLog("没找到滑块")
    }

    sleep(2000)

    //for (var i = 0; i < 0; i++) { sleep(1000); log(i); }
    while (true) {
        img = images.captureScreen();
        if (img) {
            log("截图成功。进行识别滑块！");
            break;
        } else {
            log('截图失败,重新截图');
        }
    }
    var x = discernSlidingblock(img, device.width) + 45
    console.info("识别结果滑块X坐标：" + x);

    if (x > -1) {
        randomSwipe(拖动滑块x, 拖动滑块y, x, 拖动滑块y)
        return true;
    } else {
        return false;
        console.log("识别有误，请确认是否在滑块界面");
    }
}

/**
 * 计算滑块位置
 * @param {图片} img
 * @param {分辨率} ratio
 */
function discernSlidingblock(img, ratio) {
    //创建识别变量
    var temp, temp2, x, y, num, color, p, temp3, arr1;
    //分析设备分辨率
    //红米8A
    if (ratio == 720) {
        var tb = [348, 253, 691, 638, 81]
        log("您的设备分辨率为：720p");
    } else if (ratio == 1080) {  //小米5X
        var tb = [463, 387, 912, 831, 125]
        log("您的设备分辨率为：1080p");
    } else {
        log("当前设备分辨率不符合规范")
        return -2
    }
    num = Math.ceil(tb[4] / 3.3 - 4);

    //计算滑块位置
    for (var k = 29; k <= 40; k++) {
        temp2 = "";
        color = "#" + k + "" + k + "" + k + "";
        for (var i = 1; i <= num; i++) {
            temp2 = temp2 + "0|" + i + "|" + color + ",";
            temp2 = temp2 + i + "|0|" + color + ",";
            temp2 = temp2 + "1|" + i + "|" + color + ",";
            temp2 = temp2 + i + "|1|" + color + ",";
            temp2 = temp2 + "2|" + i + "|" + color + ",";
            temp2 = temp2 + i + "|2|" + color + ",";
        }
        x = 0;
        while (x > -2) {
            y = 0;
            while (y > -2) {
                temp = "";
                for (var i = 1; i <= num; i += 2) {
                    temp = temp + "0|" + (tb[4] + y - i - 1) + "|" + color + ",";
                    temp = temp + (tb[4] + x) + "|" + i + "|" + color + ",";
                    temp = temp + (tb[4] + x) + "|" + (tb[4] + y - i - 1) + "|" + color + ",";
                    temp = temp + (tb[4] + x - i - 1) + "|0|" + color + ",";
                    temp = temp + i + "|" + (tb[4] + y) + "|" + color + ",";
                    temp = temp + (tb[4] + x - i - 1) + "|" + (tb[4] + y) + "|" + color + ",";
                    temp = temp + "1|" + (tb[4] + y - i - 1) + "|" + color + ",";
                    temp = temp + (tb[4] + x - 1) + "|" + i + "|" + color + ",";
                    temp = temp + (tb[4] + x - 1) + "|" + (tb[4] + y - i - 1) + "|" + color + ",";
                    temp = temp + (tb[4] + x - i - 1) + "|1|" + color + ",";
                    temp = temp + i + "|" + (tb[4] + y - 1) + "|" + color + ",";
                    temp = temp + (tb[4] + x - i - 1) + "|" + (tb[4] + y - 1) + "|" + color + ",";
                }
                temp = temp + temp2 + "0|0|" + color;
                arr1 = temp.split(",");
                var arr2 = new Array();
                for (var i = 0; i < arr1.length - 1; i++) {
                    arr2[i] = new Array();
                    temp3 = arr1[i].split("|");
                    arr2[i] = [Number(temp3[0]), Number(temp3[1]), temp3[2]];
                }
                try {
                    p = images.findMultiColors(img, color, arr2, {
                        region: [tb[0], tb[1], tb[2] - tb[0], tb[3] - tb[1]],
                        threshold: (Math.floor(k / 10) * 16 + k % 10)
                    });
                    if (p) {
                        img.recycle();
                        return p.x
                    }
                } catch (error) {
                    //出错
                    console.log("识别失败，错误原因：" + error);
                    return -1;
                }
                y = --y;
            }
            x = --x;
        }
    }
    try {
        img.recycle();
    } catch (error) {
        console.log("识别失败，错误原因：" + error);
    }
    return -1;
}

/**
 * 真人模拟滑动函数 （滑块滑动）
 * @param {起点x} sx
 * @param {起点y} sy
 * @param {终点x} ex
 * @param {终点y} ey
 */
function randomSwipe(sx, sy, ex, ey) {
    //设置随机滑动时长范围
    var timeMin = 1000
    var timeMax = 3000
    //设置控制点极限距离
    var leaveHeightLength = 500

    //根据偏差距离，应用不同的随机方式
    if (Math.abs(ex - sx) > Math.abs(ey - sy)) {
        var my = (sy + ey) / 2
        var y2 = my + random(0, leaveHeightLength)
        var y3 = my - random(0, leaveHeightLength)

        var lx = (sx - ex) / 3
        if (lx < 0) { lx = -lx }
        var x2 = sx + lx / 2 + random(0, lx)
        var x3 = sx + lx + lx / 2 + random(0, lx)
    } else {
        var mx = (sx + ex) / 2
        var y2 = mx + random(0, leaveHeightLength)
        var y3 = mx - random(0, leaveHeightLength)

        var ly = (sy - ey) / 3
        if (ly < 0) { ly = -ly }
        var y2 = sy + ly / 2 + random(0, ly)
        var y3 = sy + ly + ly / 2 + random(0, ly)
    }

    //获取运行轨迹，及参数
    var time = [0, random(timeMin, timeMax)]
    var track = bezierCreate(sx, sy, x2, y2, x3, y3, ex, ey)


    log("随机控制点A坐标：" + x2 + "," + y2)
    log("随机控制点B坐标：" + x3 + "," + y3)
    log("随机滑动时长：" + time[1])

    //滑动
    gestures(time.concat(track))
}

/**
 * 计算滑动轨迹
 */
function bezierCreate(x1, y1, x2, y2, x3, y3, x4, y4) {
    //构建参数
    var h = 100;
    var cp = [{ x: x1, y: y1 + h }, { x: x2, y: y2 + h }, { x: x3, y: y3 + h }, { x: x4, y: y4 + h }];
    var numberOfPoints = 100;
    var curve = [];
    var dt = 1.0 / (numberOfPoints - 1);

    //计算轨迹
    for (var i = 0; i < numberOfPoints; i++) {
        var ax, bx, cx;
        var ay, by, cy;
        var tSquared, tCubed;
        var result_x, result_y;

        cx = 3.0 * (cp[1].x - cp[0].x);
        bx = 3.0 * (cp[2].x - cp[1].x) - cx;
        ax = cp[3].x - cp[0].x - cx - bx;
        cy = 3.0 * (cp[1].y - cp[0].y);
        by = 3.0 * (cp[2].y - cp[1].y) - cy;
        ay = cp[3].y - cp[0].y - cy - by;

        var t = dt * i
        tSquared = t * t;
        tCubed = tSquared * t;
        result_x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
        result_y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
        curve[i] = {
            x: result_x,
            y: result_y
        };
    }

    //轨迹转路数组
    var array = [];
    for (var i = 0; i < curve.length; i++) {
        try {
            var j = (i < 100) ? i : (199 - i);
            xx = parseInt(curve[j].x)
            yy = parseInt(Math.abs(100 - curve[j].y))
        } catch (e) {
            break
        }
        array.push([xx, yy])
    }

    return array
}

function dianji_hongbao() {
    if (device.model == "Mi Note 3") {
        var red_packet = id("red_packet").findOne(2000);
    }
    else if (device.model == "MI NOTE Pro" || device.model == "Redmi 8A" ) {
        var red_packet = id("redFloat").findOne(2000);
    }
    else {
        var red_packet = id("red_packet").findOne(2000);
    }
    
    if (red_packet) {
        toastLog("开始点击红包")
        click_button( red_packet.bounds())
    }
}

function check_sign_success(){
    sleep(2000)
    for(var i = 0 ;i<2;i++){
        var success = textStartsWith("签到成功加").findOne(2000)
        //关闭邀请
        if (success) {
            // insert to db
            success.parent().parent().child(0).click()
            toastLog("已验证签到成功！退出！");
            return true;
        }
        else{
            var 重试 = text("重试").findOne(2000)
            if( 重试 ){
                重试.click() 
            }
        }
    }
    
    sleep(1000);
    return false;
}

//领取任务
function handle_get_task( taskstr ){
    toastLog("处理领取任务");
    sleep( 2000 )
    //先处理广告
    err_handle()
    for(var i = 0;i<2;i++){
        var target_button = find_button_by_textStartsWith( taskstr )
        if( target_button ){ 
            if( taskstr == "三餐领金币" ){
                click_button( target_button.parent().parent().child(2).bounds() )
                err_handle()
                //点击频率过快
            }
            else{
                click_button( target_button.bounds() )
                err_handle()
            }
            break
        }
        else{
            toastLog( taskstr + "按钮未找到" )
            err_handle()
        }
    }
    
    return 0
}


//处理获得更多奖励的流程
function handle_more_reward_task(){
    toastLog("处理双倍任务");
    sleep( 2000 )
    //签到成功触发看视频再奖励按钮
    var strlist = ["金币翻倍"]
    var target_button = null
    for( var i = 0 ;i < strlist.length ; i++ ){
        target_button = find_button_by_textStartsWith( strlist[i] )
        if(target_button){
            toastLog( target_button.text() )
            break;
        }
    }
    if( target_button ){
        click_button( target_button.bounds() )
        if( handle_after_more_reward() >= 0 ){
            toastLog( "处理双倍任务完成")
            click_close()
        }
        else{
            toastLog( "处理双倍任务失败")
            return -1
        }
    }
    else{
        //看视频再奖励流程失败
        toastLog("没找到双倍任务按钮");
        return -1
    }
    return 0 
}

function handle_shouye_get_task() {
    toastLog("处理首页领取任务")
    sleep(2000)
    var 首页 = find_button_by_textStartsWith( "首页")
    for(var i = 0 ; i <2; i++){
        if( 首页 ){
            click_button( 首页.bounds() )
            //会有弹窗广告
    
            //收取金币
            for(var i = 0 ;i <2 ;i++){
                let shouqu = id("iv_item_pig_status").findOne(5000);
                if(shouqu) {
                    toastLog("收取金币")
                    shouqu.click()
                    handle_more_reward_task();
                    click_close()
                    sleep(2000)
                    break
                }
                else{
                    toastLog("收取金币失败")
                    err_handle()
                }
            }
            
            //领取财神
            for(var i = 0 ;i <2 ;i++){
                let caishen = id("tv_main_coupon_achieve").text("可领取").findOne(2000);
                if(caishen) {  
                    toastLog("领取财神")
                    caishen.parent().click();
                    let caishen_fanbei = text("财神翻倍").findOne(2000);
                    if(caishen_fanbei) {
                        toastLog("财神翻倍");
                        caishen_fanbei.click();
                        click_close()
                        handle_after_more_reward();
                        sleep(1000);   
                    }
                    break
                }
                else{
                    toastLog("没有可领取财神")
                    //会有弹窗广告
                    err_handle()
                }
            }
            
    
            //使用财神
            for(var i = 0 ;i <2 ;i++){
                let use_caishen = id("tv_main_use_coupon").text("使用").findOne(2000); //不一定找到
                let coupon_count_obj = id("tv_main_coupon_count").findOne(2000);       
                if( use_caishen && coupon_count_obj ){
                    let coupon_count =parseInt(coupon_count_obj.text().replace("x", ""));
                    log("财神数量："+ coupon_count);
                    for(i=0;i<coupon_count;i++){
                        log("使用财神");
                        use_caishen.click();
                        sleep(random(800, 1200));
                        let liji_use = id("tv_pop_use_coupon_use").text("立即使用").findOne(2000);
                        if(liji_use) {
                            liji_use.click();
                            sleep(1000);
                        }
                    }
                    break
                }
                else{
                    toastLog("没有财神可使用")
                    //会有弹窗广告
                    err_handle()
                }
            }
            
            //领取红包
            for(var i = 0 ;i <2 ;i++){
                let hogbao = id("tv_main_red_pocket_achieve").text("可领取").findOne(2000);
                if(hogbao) {
                    log("领取红包");
                    hogbao.parent().click();
                    let hongbao_fanbei = text("红包翻倍").findOne(2000);
                    if(hongbao_fanbei) {
                        log("红包翻倍");
                        hongbao_fanbei.click();
                        handle_after_more_reward();
                        click_close()
                        sleep(1000);
                    }
                    break
                }
                else{
                    toastLog("没找到可领取红包")
                     //会有弹窗广告
                     err_handle()
                }
            }
    
            //会有弹窗广告
            err_handle()
            
            //视频红包   需检查红包金额
            let count = 60;
            log("领"+ count+"次红包!");
            for(i=0;i<count;i++){
                toastLog("第"+ i+"次红包任务!");
                let video_red_pocket = text("视频红包").findOne(2000);
                if(video_red_pocket) {
                    log("点击视频红包");
                    sleep(1000);
                    video_red_pocket.parent().click();
                    handle_after_more_reward();
                    var stopflag = find_button_by_textStartsWith("当日操作已达最大数")
                    if( stopflag ){
                        toastLog( stopflag.text() )
                        app_func.stopflag = stopflag.text()
                        break;
                    }
                    if(app_func.stopflag !=null){
                        toastLog( app_func.stopflag )
                        break
                    }
                    //如果金额太小跳出循环 不再点进视频红包
                    // var floatmoney = check_get_money()
                    // toastLog( floatmoney )
                    // if( typeof(floatmoney) == "number" && floatmoney > 0 ){
                    //     if( floatmoney > 0.01 ){
                    //         click_close();
                    //         continue
                    //     }
                    //     else{
                    //         toastLog("红包金额太小")
                    //         break;
                    //     }
                    // }
                    // else{
                    //     toastLog("没检测到红包金额")
                    //     err_handle()
                    // }                     
                }
                else{
                    toastLog("未找到视频红包")
                    err_handle()
                }
            }
            sleep(1000);
            toastLog("视频红包任务结束")
            break
        }
        else{
            toastLog("首页按钮寻找失败")
            err_handle()
        }
    }
    
    toastLog("首页领取类任务结束")
    return 0;
}

function check_get_money(){
    //检查获得红包金额 
    var 恭喜获得 = textMatches("恭喜获得\\d+元").findOne(5000);
    if( 恭喜获得){
        var str = 恭喜获得.text();
        var sindex = str.indexOf("得")
        var eindex = str.indexOf("元")
        var strmoney = str.substr( sindex + 1, eindex - sindex - 1 )
        toastLog( strmoney )
        return parseFloat( strmoney )
    }
    else{
        toastLog("未找到恭喜获得")
        err_handle()
        return -1
    }
}

function handle_dagong_task(){
    toastLog( "开始打工任务")
    
    sleep(2000)
    //打工
    
    let qudagong = id("ll_main_tag_3").findOne(2000);
    if(qudagong) {
        qudagong.click();
        sleep(3000);
        err_handle()
        if(device.model == "Redmi 8A") {
            swipe(random(400, 500), 1300, random(400, 500), random(1200, 1300), 900);
        }
        else{
            swipe(random(400, 500), random(1500, 1600), random(400, 500), random(1200, 1300), random(700, 1500));
        }
        sleep(1000);
        let is_working = text("在打工").findOne(2000) ? true: false;
        if( is_working ){
            toastLog("已经在打工了")
            return 0
        }
        
        let lingjiangli = text("领奖励").findOne(2000);
        if(lingjiangli) {
            lingjiangli.click();
            sleep(1000);
            let fanbei = text("红包翻倍").findOne(2000);
            if(fanbei){
                log("红包翻倍");
                fanbei.click();
                handle_after_more_reward()
                sleep(1000);
            }
            click_close();
        }
        
        let dagong = id("tv_working_do_5").text("去打工").findOne(1000);
        if(dagong) {
            log("点击去打工");
            dagong.click();
            sleep(1000);
        }

        dagong = id("tv_working_do_4").text("去打工").findOne(1000);
        if(dagong) {
            log("点击去打工");
            dagong.click();
            sleep(1000);
        }
    }
    else{
        toastLog( "没有找到打工界面")
        return -1
    }
    return 0
}

function thread_close_all_ad(){
    var runtimes = 0
    app_func.thread = threads.start(function(){
        toastLog("启用关闭弹窗线程")
        while( !app_func.taskEnd ){
            sleep(5000)
            close_all_ad()
            runtimes++
        } 
        app_func.thread.interrupt();
        toastLog("退出弹窗处理线程")
    })
    return 
}

function err_handle(){
    //会有弹窗广告
    if( !is_mainAct() ){
        close_all_ad()
        handle_after_more_reward()
    }
    else{
        close_all_ad()
    }
}

function check_huadongyanzhengma() {
    var widget = text("拖动滑块").findOne(1000);
    if (widget) {
        sleep(1000);
        openScreenCapture();
        dragSlider();
    }
}

function handle_watch_video(){
    var index = 0;
    var count = 40
    var random_min = 5000
    var random_max = 10000
    var w = device.width
    var h = device.height

    if (count == 0) {return}
    toastLog("即将滑动" + count + "次！");

    if ( is_videoAct() ) {
        while (index <= count) {
            check_invate();
            check_qingshaonian();
            check_huadongyanzhengma();
            sml_move(w / 2, h * 0.8 + h * random() * 0.1, w / 2, h * 0.15, 200 + 600 * random());
            var random_time = random(random_min, random_max);
            toastLog("观看"+ app_func.appName +"第" + index + "/"+ count +"个视频中...");
            toastLog("预计时长"+ (random_time/1000) + "秒~");
            sleep(random_time);
            index++;
        }
    }
    else{
        toastLog( "不在视频页面")
        var 重试 = text("重试").findOne(2000)
        if( 重试 ){
            重试.click() 
        }
        if( is_mainAct() ){
            back()
        }
        //处理滑块或者各种广告
    }
}

function check_invate() {
    var close = id("close").findOne(1000)
    if(close) {
        sleep(1000);
        close.click()    
    }
    
    var widget = text("每邀请1个好友可得现金").findOne(1000);
    if (widget) {
        toastLog("发现邀请页面！")
        sleep(1000);
        back();
    }
    
}

function check_qingshaonian() {
    var widget = text("我知道了").findOne(1000);
    if (widget) {
        widget.click();
        sleep(1000);
    }
}

function kanshipin(){
    toastLog("看精彩视频")
    var 每次100金币 = auto_find_button("每次100金币")
    if(每次100金币){
        var dotimes = 0 //准备观看次数
        var str = 每次100金币.text()
        toastLog(str);
        var index = str.indexOf("/")
        var num2 = str[index-1]
        var num1 = str[index-2]
        if( num2 == '0' && num1=='1'){
            dotimes = 0
            toastLog("看视频任务已完成");
            return 0
        }
        else{
            dotimes = 10-num2
        }
        
        var 福利 = text("福利").findOne(2000)
        if( 福利 ){
            for( var i = 0 ; i < dotimes ; i++ ){
                sleep( 5000 )
                try {
                    福利.click()
                    close_time_adv()
                } catch (error) {
                    console.log(error )
                }   
            }
        }
        toastLog("任务完成")
        return 0
    }
    else{
        toastLog("没有找到看精彩视频")
        return -1
    }
}

//处理倒计时广告
function close_time_adv(){
    //总时间为 广告时间X单次寻找等待时间
    let 广告时间 = 30
    for(var i = 0 ; i < 广告时间 ; i++){
        sleep(1000)
        //每5秒检查一次关闭按钮是否出现
        if( (i+1) % 5 == 0 ){
            //寻找时间到的线索
            if( find_end_state_button() >= 0 ||
                find_X_adv_button() >= 0 ){  

                继续观看 = find_button_by_textStartsWith("继续观看")
                if(继续观看)
                {
                    click_button( 继续观看.bounds() )
                    continue
                }
            }
            if( is_mainAct() ){ //任务act 也应该视为广告已不存在
                return 0
            }
        }    
    }
    return -1; 
}

//寻找 没有倒计时存在后  back
function find_end_state_button(){
    var back_button = text("点击重播").findOne( 1000 )
    var cli_button = null
    if( back_button ){
        toastLog("发现关闭时机");
        back()
        return 0
    }//出现刚开始是关闭广告过两秒才开始倒计时的情况
    else if( cli_button = text("关闭广告").findOne(1000) ){
        sleep(3000)
        cli_button = text("关闭广告").findOne(1000) 
        if( cli_button ){
            toastLog("关闭广告");
            click_button(cli_button.bounds()) 
            return 0
        }
    }
    else{
        //寻找关闭按钮
        关闭 = text("关闭").findOne(1000)
        if(关闭){ //有假关闭按钮统一back
            back()
            return 0
        }
    }
    return -1   
}

//寻找img类型关闭按钮
function find_X_adv_button(){
    //点击下载出现的时候   倒计时控件不存在的时候
    var close = 
    id("tt_video_ad_close").findOne(1000) || 
    id("tt_video_ad_close_layout").findOne(1000)
    if( close ){
        toastLog("发现关闭按钮");
        click_button( close.bounds() );
        return 0
    }
    else{
        //支付宝三连
        //弹支付宝   取消安装   关闭按钮
        try {
            取消 = text("取消").findOne(500)
            if( 取消 ){
                click_button(取消.bounds())
                toastLog("11")
            }         
        } catch (error) {  
        }
        try {
            关闭 = text("关闭").findOne(500)
            if( 关闭 ){
                click_button(关闭.bounds())
                toastLog("22")
            }         
        } catch (error) {  
        }
        try {//支付宝
            if( currentPackage() != config.packageName ){
                sleep(2000)
                back()
                sleep(2000)
                继续=textStartsWith("继续").findOne(1000)
                toastLog("33")
                if(继续){
                    click_button( 继续.bounds() )
                    toastLog("44")       
                }
            }       
        } catch (error) {  
        }
    }
    return -1
}

app_func.main = function(){
    console.log("start...");
    var open_app = launchAppEnhance( app_func.appName );  

    if( open_app ){
        sleep(5*1000)
        toastLog("启动成功")

        //先签到
        if( handle_sign_task() < 0 ){
            toastLog( "签到任务失败")
        }

        kanshipin()

        if(is_mainAct) //在任务界面
        {
            back() //进入视频页面
        }

        handle_watch_video()  

        toastLog("任务已执行完毕")
    }
    else{
        console.log("app启动失败");
    }

    console.log("end...");
    app_func.taskEnd = true
}



try {
    app_func.main();
} catch (error) {
    toastLog( error );
}

var storage = storages.create("xiangxiangyuedu");
storage.put("script_running_status", "end");